class User < ActiveRecord::Base
  has_many :usernames, :dependent => :destroy
  has_and_belongs_to_many :roles, :join_table => Authorization.table_name
  has_many :mappings, :class_name => "Map"
  belongs_to :default_mapping_type, :class_name => "MappingType"

  after_update :save_usernames

  validates_presence_of :fname, :lname, :email
  validates_associated :usernames
  # regex taken from rails api docs
  validates_format_of :email, :message => "must be a properly formatted email address", :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i

  def fullname
    self.fname + " " + self.lname
  end

  def new_username_attributes=(username_attributes)
    username_attributes.each do |attributes|
      attributes[:authentication_type_id] ||= 2
      self.usernames.build(attributes)
    end
  end

  def existing_username_attributes=(username_attributes)
    self.usernames.reject {|u| u.new_record?}.each do |username|
      attributes = username_attributes[username.id.to_s]
      if attributes
        username.attributes = attributes
      else
        self.usernames.delete(username)
      end
    end   
  end

  def save_usernames
    self.usernames.each do |username|
      username.save(false)
    end
  end

  def admin?
    roles = self.roles.select {|r| r.name == "admin"}
    return roles.size > 0
  end

end
